#ifndef TASK_H
#define TASK_H

#include<cstring>
#include<pthread.h>
#include <fstream> 

class Task {
private:
	int id;
	char* buffer;
	int length;
	bool done;
	pthread_mutex_t  cond_lock;
	pthread_cond_t cond;
public:
	Task(int task_id, char* buf, int len) : id(task_id), buffer(new char[len]), length(len), done(false) {
		pthread_mutex_init(&cond_lock,NULL);
		pthread_cond_init(&cond,NULL);
		memcpy(buffer,buf, sizeof(char)*len);
	}
	
	~Task() {
		delete [] buffer;
		pthread_mutex_destroy(&cond_lock);
		pthread_cond_destroy(&cond);
	}
	
	
	
	int get_id() {
		return id;
	}
	
	int writeTask(std::ofstream& out) {
		int error=0;
		error |= pthread_mutex_lock(&cond_lock);
		
		try{
		out.write(buffer,length);
		out.flush();
		}
		catch(std::ios_base::failure e) {
			std::cerr << "system error" << std::endl;
		}
		done=true;
		
		pthread_cond_broadcast(&cond);
		
		error |= pthread_mutex_unlock(&cond_lock);
		
		
		return error;
	}

	int wait_on_me() {
		int error=0;
		error |= pthread_mutex_lock(&cond_lock);
		
		if(!done) { //if we aren't done executing wait on the conditional variable
			error |= pthread_cond_wait(&cond,&cond_lock);
		}
		
		error |= pthread_mutex_unlock(&cond_lock);
		return error;
	}
};

#endif